//
//  PKPricingPlansViewController.swift
//  GoAbroad
//
//  Created by Pink Snow on 2025/5/14.
//

import UIKit
import SnapKit
import SwiftEntryKit
import StoreKit
class PKPricingPlansViewController: PKBaseViewController,NavigationBarConfigurable ,UICollectionViewDataSource,UICollectionViewDelegate{

    
    private var collectionView: UICollectionView!
    var shouldHideNavigationBar: Bool { true}
    var showBackButton: Bool { false}
    let backButton = UIButton(type: .custom)
    let titleLabel = UILabel()
    var dataArray : [PKPriceModal]?
    private let plans = [
        PricingPlan(title: "Free", price: "$0 /month", description: "Basic plan for individual users",
                    features: ["10 image generations per month", "Standard resolution", "Basic support"],
                    isPopular: false, buttonTitle: "No Subscription Required"),
        
        PricingPlan(title: "Premium", price: "$5 /month", description: "Basic package for individual users",
                    features: ["200 image generations per month", "High-resolution image downloads", "Ad-free experience", "No watermark"],
                    isPopular: true, buttonTitle: "Upgrade Plan"),
        
        PricingPlan(title: "Ultimate", price: "$10 /month", description: "Full-featured unlimited package",
                    features: ["500 image generations per month", "High-resolution image downloads", "Faster generation speed", "Early access to new features", "Ad-free experience", "No watermark"],
                    isPopular: false, buttonTitle: "Upgrade Plan")
    ]
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //        updateNavBarVisibility(animated: animated)
    }
    
    override func setupUI() {
        //        title = "Choose Plan"
        
        
        
        
        
        
        view.backgroundColor = .white
        titleLabel.text = "Subcription plans"
        titleLabel.font = .adaptedBoldFont(size: 18)
        
        view.addSubview(titleLabel)
        
        backButton.setImage(.init(named: "back"), for: .normal)
        view.addSubview(backButton)
        backButton.snp.makeConstraints { make in
            make.left.equalTo(ScreenAdapter.x(20))
            make.top.equalTo(DeviceHelper.navigationBarHeight + 20)
            make.width.height.equalTo(ScreenAdapter.x(30))
        }
        
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(DeviceHelper.navigationBarHeight+20)
        }
        
        backButton.rx.tap.subscribe { _ in
            self.navigationController?.popViewController(animated: true)
        }.disposed(by: rx.disposeBag)
        setupNavigationBar()
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        
        layout.itemSize = .init(width: ScreenAdapter.baseWidth * 0.8, height: 380)
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .white
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(PKPricingPlansCollectionViewCell.self, forCellWithReuseIdentifier: PKPricingPlansCollectionViewCell.identifier)
        collectionView.showsHorizontalScrollIndicator = false
        
        view.addSubview(collectionView)
        //               collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(DeviceHelper.navigationFullHeight+20)
            make.centerX.equalToSuperview()
            make.width.equalTo(ScreenAdapter.baseWidth * 0.8+20)
            make.bottom.equalTo(-DeviceHelper.bottomSafeAreaHeight-10)
        }
        self.startAnimating()
        NetworkManager.shared.requestAuthArray(.getSubscribplans, type: PKPriceModal.self,using: NetworkManager.shared.authprovider).subscribe { [self] modal in
            
            //            print(modal)
            dataArray = modal
            printG(dataArray)
            collectionView.reloadData()
            self.stopAnimating()
        }onError: { error in
            self.stopAnimating()
        } onCompleted: {
            print("com")
        }.disposed(by: rx.disposeBag)
        
        
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let data = dataArray {
            return data.count
        }else{
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        var plan = plans[indexPath.row]
        var modal = dataArray![indexPath.item]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PKPricingPlansCollectionViewCell.identifier, for: indexPath) as! PKPricingPlansCollectionViewCell
        cell.configure(with: plan,modal)
        
        cell.cellTapBehavior.filter({ string in
            return string.count != 0
        }).subscribe { [self] _ in
            
            
            let alert = UIAlertController(title: "Tips", message: "Whether to purchase a subscription or not.？", preferredStyle: .alert)

            alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in
                
            }))
            alert.addAction(UIAlertAction(title: "Enter", style: .destructive, handler: { [self] _ in
                print(indexPath)
                if let dataArray = dataArray {
                    let model = dataArray[indexPath.row]
                    // 使用 model
                    self.startAnimating()
                    NetworkManager.shared.requestAuthObject(.appPayOrder(code: model.productID!), type: PKOrderModal.self, using: NetworkManager.shared.authprovider).subscribe { [self] modal in
                        //                print(modal.session_id)
                        IAPManagerOne.shared.order_id = modal.session_id
                        //                IAPManagerOne.shared.purchase(productID: "com.goabroad.weak")
    //                    model.pro
                        IAPManagerOne.shared.product = model.productID
                        IAPManagerOne.shared.fetchProducts(productIdentifiers: [model.productID ?? ""])
                        IAPManagerOne.shared.managerSubject?.filter({ base64 in
                            return base64.count != 0
                        }) .subscribe { [self] base in
                            if base == "error"{
                                self.stopAnimating()
                                var descriptionString: String
                    //                    var descriptionThumb: String
                                descriptionString = "Be Recharged Failed!"
                                
                                Popup.shared.showNotificationMessage(attributes: Popup.shared.attributes(), title: "Tips", desc: descriptionString, textColor: EKColor(.white))
                            }else{
                                NetworkManager.shared.requestAuthObject(.applePayVerify(receipt: base, orderid: IAPManagerOne.shared.order_id!), type: PKAppleReceipModal.self, using: NetworkManager.shared.authprovider).subscribe { modal in
                                    self.stopAnimating()
                                    var descriptionString: String
                        //                    var descriptionThumb: String
                                    descriptionString = "Be Recharged Successfully!"
                                    
                                    Popup.shared.showNotificationMessage(attributes: Popup.shared.attributes(), title: "Tips", desc: descriptionString, textColor: EKColor(.white))
                               
                             //     Popup.shared.showPopupMessage(attributes: Popup.shared.attributes(), title: "eee", titleColor: EKColor(.white), description: descriptionString, descriptionColor: EKColor(.yellow), buttonTitleColor: EKColor(.orange), buttonBackgroundColor: EKColor(.green))
                                }onError: { error in
                                    self.stopAnimating()
                                    print(error)
                                    
                                }onCompleted: {
            //                        self.stopAnimating()
                                }.disposed(by: rx.disposeBag)
                            }
                            print("测试")
                            
                     
                        }onError: { error  in
                            self.stopAnimating()
                        }onCompleted: {
                            
                        }.disposed(by: rx.disposeBag)
                    }.disposed(by: rx.disposeBag)
                    
                    
                }
            }))

            present(alert, animated: true, completion: nil)
            
            
            
            
       
        
            
            
            
        }.disposed(by: rx.disposeBag)
        
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //        let checkout  = PKCheckOutViewController()
        //        self.navigationController?.pushViewController(checkout, animated: true)
        //
        //        let pay = PKPaymentStoreViewController()
        //        self.navigationController?.pushViewController(pay, animated: true)
        
        
        
    }
    
    //     func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
    //                         sizeForItemAt indexPath: IndexPath) -> CGSize {
    //         return CGSize(width: DeviceHelper.screenWidth - 32, height: 360)
    //     }
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */
    
}
